package com.com.hefei.wdp.example.service;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
//hystrix全局配置熔断配置 低于局部配置
@DefaultProperties(defaultFallback="timeoutHandler",commandProperties = {
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="5000") //超过三秒
    })
public class ProducerService {
    @Value("${server.port}")
    private Integer port;

    @Value("${spring.application.name}")
    private String SpringApplicationName;
// ******************* 服务降级 ***********************
    // 局部控制
//    @HystrixCommand(fallbackMethod = "timeoutHandler",commandProperties = {
//            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="5000") //超过三秒
//    })
    @HystrixCommand  //@DefaultProperties + @HystrixCommand  实现全局配置
    public String getAppInfo() throws InterruptedException {
        TimeUnit.SECONDS.sleep(3);
//        int a = 10/0;
        return SpringApplicationName+" : "+port;
    }


    public String timeoutHandler(){
        return "超时。。。。";
    }

// ******************* 服务熔断 ***********************
    // 在时间窗口期内，在请求次数内，失败率达到60% 就跳闸
    // 局部配置，细粒度配置
    @HystrixCommand(fallbackMethod = "timeoutHandler2",commandProperties = {
            @HystrixProperty(name="circuitBreaker.enabled",value="true") , //是否开启断路器
            @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10") ,// 请求次数
            @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000") ,//时间窗口期，10000ms
            @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value="60") ,// 失败率达到多少次跳闸，执行熔断方法
    })
    public String getAppInfo2(Integer id ) throws InterruptedException {
    //    TimeUnit.SECONDS.sleep(3);
    //        int a = 10/0;
        if(id>0){
            return SpringApplicationName+" : "+port+"---------";
        }else {
            throw  new RuntimeException("错误");
        }

    }


    public String timeoutHandler2(Integer id ){
        return "熔断。。。。";
    }



}
